package com.hyk.service.impl;

import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.hyk.domain.User;
import com.hyk.feign.JwtToken;
import com.hyk.feign.OAuth2FeignClient;
import com.hyk.geetest.GeetestAutoConfiguration;
import com.hyk.geetest.GeetestLib;
import com.hyk.model.LoginUser;
import com.hyk.service.UserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.bind.ValidationException;

@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {

    @Resource
    private OAuth2FeignClient oAuth2FeignClient;

    @Value("${basic.token:Basic Y29pbi1hcGk6Y29pbi1zZWNyZXQ=}")
    private String basicToken;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private GeetestLib geetestLib;

    @Override
    public LoginUser login(User loginForm) throws ValidationException {
        //校验参数
        GeetestAutoConfiguration.checkGeetest(loginForm,redisTemplate,geetestLib);

        //获取token
        // 登录就是使用用户名和密码换一个token 而已--->远程调用->authorization-server
        ResponseEntity<JwtToken> tokenResponseEntity = oAuth2FeignClient.getToken("password", loginForm.getUsername(), loginForm.getPassword(), "member_type", basicToken);
        if (tokenResponseEntity.getStatusCode() != HttpStatus.OK) {
            throw new ApiException("用户名或密码错误");
        }
        JwtToken jwtToken = tokenResponseEntity.getBody();
        // 封装返回值
        LoginUser loginUser = new LoginUser(loginForm.getUsername(),
                jwtToken.getTokenType() + " " + jwtToken.getAccessToken(),
                jwtToken.getRefreshToken(),
                jwtToken.getExpiresIn());
        // 使用网关解决登出的问题:
        // token 是直接存储的
        //stringRedisTemplate.opsForValue().set(jwtToken.getAccessToken(), "", jwtToken.getExpiresIn(), TimeUnit.SECONDS);
        return loginUser;
    }


}
